package com.hu.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.auth.mapper.RoleMapper;
import com.hu.auth.mapper.UserRoleMapper;
import com.hu.auth.model.Role;
import com.hu.auth.model.UserRole;
import com.hu.auth.model.po.AssignRolePo;
import com.hu.auth.model.po.RolePo;
import com.hu.auth.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    RoleMapper roleMapper;
    @Resource
    UserRoleMapper userRoleMapper;

    @Override
    public void add(RolePo po) {
        Role role = new Role();
        role.setRoleCode(po.getRoleCode());
        role.setRoleName(po.getRoleName());
        if (po.getDescription() != null) {
            role.setDescription(po.getDescription());
        }
        roleMapper.insert(role);
    }

    // 获取用户的角色
    @Override
    public Map<String, Object> getByUserId(Long userId) {
        // 全部角色
        List<Role> roleList = roleMapper.selectList(null);
        // 用户角色id
        List<Long> roleIdList = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId))
                .stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("roleList", roleList);
        map.put("roleIdList", roleIdList);
        return map;
    }

    // 为用户分配角色
    @Override
    public void assignRole(AssignRolePo po) {
        // 删除原来之前有的
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, po.getUserId()));
        // 分配
        UserRole userRole = new UserRole();
        userRole.setUserId(po.getUserId());
        po.getRoleIdList().forEach(roleId -> {
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        });
    }


}
